# #!/usr/bin/env python
# coding=utf-8
import os
import threading
import subprocess

import sys
print(os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
print(sys.path)



"""
将wmv转换成mp4的函数
传入的是文件地址和输出地址
"""
def wmvtomp4(wmvfilename, root):
    # wmvfilename = "201801071244512ddb9b5c056246a9a5e7a4b345fe90db.wmv"
    array = wmvfilename.split('.')
    array.pop()
    array.append('mp4')
    separator = '.'
    filename = separator.join(array)
    string = "ffmpeg -i " + wmvfilename + " -vcodec libx264 -acodec aac -strict -2 " + filename
    try:
        subprocess.check_call("cd " + root, shell=True)
        subprocess.check_call(string, shell=True)
    except subprocess.CalledProcessError as err:
        print("转换出现错误")
        print(err)


"""
开多线程进行转换
"""


def startconversion(filename, root):
    thread = threading.Thread(target=wmvtomp4, args=(filename, root))
    thread.start()


"""
获取某个目录下的文件 不包含子目录
"""
def getListFiles(path):
    assert os.path.isdir(path), '%s not exist.' % path
    ret = []
    for root, dirs, files in os.walk(path):
        print('%s, %s, %s' % (root, dirs, files))
        for filespath in files:
            ret.append(os.path.join(root, filespath))
            # ret.append((root, filespath))
    return ret


"""
获取顶层目录
"""


def getTopDir():
    topdir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
    return topdir


"""
获取静态文件目录
"""


def getStaticFileDir():
    topdir = getTopDir()
    staticdir = "/movieapp/app/static/uploads"
    return topdir + staticdir


def run():
    # 通过静态文件目录获取文件列表
    ret = getListFiles(getStaticFileDir())
    # 循环文件列表获取每个视频文件
    for file in ret:
        # 将视频文件拆分以便获取后缀
        array = file.split('.')
        if len(array) >= 2:
            # 判断后缀是不是WMV
            if array[1] == 'wmv':
                # 通过路径拆分
                patharray = file.split('/')
                # 获取文件名
                filename = patharray[-1]
                # 去除列表中最后一个，最后一个是文件名
                patharray.pop()
                # 将路径重新组合
                pathdir = '/'.join(patharray)
                # 这样就获取到了文件名和路径
                print(pathdir, filename)
                # 将文件名和文件路径传入函数
                startconversion(file, pathdir)


if __name__ == "__main__":
    # from xjlibrary.mprocesspoll.mythreading import thread_pool
    # thread_pool.add_job(run)
    pass
